package com.ocm.tourism.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ocm.tourism.core.domain.AuditInfo;
import com.ocm.tourism.core.domain.Business;
import com.ocm.tourism.core.domain.BusinessType;
import com.ocm.tourism.core.model.UserInfo;
import com.ocm.tourism.core.service.AuditService;
import com.ocm.tourism.core.util.TourismUtil;
import com.ocm.tourism.core.util.UserUtil;

public class AuditInterceptor extends HandlerInterceptorAdapter {

   @Autowired
   private AuditService auditService; 
   
   private String businessType;
   
   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
         ModelAndView modelAndView) throws Exception {
      saveAuditInfo(request, modelAndView);
      super.postHandle(request, response, handler, modelAndView);
   }

   private void saveAuditInfo (HttpServletRequest request, ModelAndView modelAndView){
      BusinessType businessTypeName = BusinessType.getBusinessType(businessType);
      Business business = null;
      switch (businessTypeName) {
         case HOTEL:
            business = (Business) modelAndView.getModel().get("hotel");
            break;
      }
      if (business != null){
         AuditInfo auditInfo = new AuditInfo();
         auditInfo.setAccessedDate(new Date(System.currentTimeMillis()));
         auditInfo.setSessionid(request.getSession().getId());
         auditInfo.setBusinessType(business.getBusinessType());
         auditInfo.setBusinessId(business.getId());
         UserInfo userInfo = UserUtil.getAuthenticated();
         if (userInfo != null){
            auditInfo.setLoggeduser(userInfo.getUsername());
         }
         String auditKey = TourismUtil.createAuditKey(auditInfo.getBusinessId(), auditInfo.getSessionid(), auditInfo.getLoggeduser());
         if (!auditService.hasExistedAudit(auditKey)){
            auditInfo.setAuditKey(auditKey);
            auditService.saveAudit(auditInfo);
         }
      }
   }
   public String getBusinessType() {
      return businessType;
   }

   public void setBusinessType(String businessType) {
      this.businessType = businessType;
   }
}
